#!/usr/bin/python3

#在1.6_test_all_die_output/03/result/CPU2017.XXX.log中提取起止时间,ratio和试验编号YYY
#根据实验编号进入相应文件夹test_1.6_max_all_die_YYY,提取起止时间内的平均功耗

import os
import sys
import re
from datetime import datetime

FILE_NAME=r'CPU2017.\d{3}.log'
FILE_PATH=None
DIRECTORY_NAME='/test_1.6_max_all_die_'
DIRECTORY_PATH=None

def openDirectory(directoryPath):#获取目录下的所有文件
    files=list()
    for file in os.listdir(directoryPath):
        file_path=os.path.join(directoryPath,file)
        files.append(file_path)
    return files

def addFiles(filePath,fileName):#添加符合匹配规则的所有文件
    files=list()
    for file in os.listdir(filePath):
        if re.match(fileName,file):
            file_path=os.path.join(filePath,file)
            files.append(file_path)
    return files
    
def getData(filepath,start,end):#输入一个文件和首尾字符串，返回两字符串之间的内容
    with open(filepath,'r') as f:
        file_content=f.read()
        start_index=file_content.find(start)
        end_index=file_content.find(end,start_index+len(start))
        if start_index==-1 or end_index==-1:
            return None
        return str(file_content[start_index+len(start):end_index])

def getTime(date):
    dt=datetime.strptime(date,'%Y-%m-%d %H:%M:%S')
    return str(dt.time())

def getDate(date):
    dt=datetime.strptime(date,'%Y-%m-%d %H:%M:%S')
    return str(dt.date())

def getStartTime(fileName):
    date=getData(fileName,'Run Start:    ',' (')
    if date==None:
        return None
    else:
        return getTime(date)
    
def getStartDate(fileName):
    date=getData(fileName,'Run Start:    ',' (')
    if date==None:
        return None
    else:
        return getDate(date)

def getStopTime(fileName):
    date=getData(fileName,'Run Stop:     ',' (')
    if date==None:
        return None
    else:
        return getTime(date)

def getTestNumber(fileName):
    return getData(fileName,'Success: 1x','.')

def getCPUratio(fileName):
    return getData(fileName,'ratio=',',')

def getAvePowCsum(filePath,start_time,end_time):
    with open(filePath,'r') as f:
        total=0
        count=0
        for line in f.readlines():
            line_time=line.split()[0]
            if start_time <= line_time <= end_time:
                value=float(line.split()[-1])
                total+=value
                count+=1
    if count==0:
        return 0
    else:
        return round(total/count,3)

testNumbers=sys.argv[1:] #获取外部输入的实验编号
if len(testNumbers)==0: # 如果没有输入，打印报错信息并退出
    print('Plesae input testNumber!')
    exit()
while FILE_PATH==None or DIRECTORY_PATH==None: #用户输入log文件所在的路径和数据文件所在的路径
    print('Please input the directory path of the log file')
    FILE_PATH=input()
    print('Please input the directory path of the data file')
    DIRECTORY_PATH=input()
data=list()
dir0=addFiles(FILE_PATH,FILE_NAME) #添加所有符合匹配规则的log文件
for file in dir0:
    date=getStartDate(file)
    StartTime=getStartTime(file)
    StopTime=getStopTime(file)
    ratio=getCPUratio(file)
    if StartTime==None or StopTime==None or ratio==None: #存在无效文件的情况，任意一项为空便跳过
        continue
    testNumber=getTestNumber(file)
    if testNumber not in testNumbers: #只处理用户输入的实验编号
        continue
    dir1=openDirectory(DIRECTORY_PATH+DIRECTORY_NAME+str(testNumber)) #根据实验编号打开目录，获取全部文件
    avePowCsum=0
    for file in dir1:
        avePowCsum=getAvePowCsum(file,StartTime,StopTime) #计算平均功耗
        if avePowCsum!=0: #获取到平均功耗便退出
            break
    if avePowCsum!=0:
        data.append([testNumber,date,StartTime,ratio,avePowCsum]) #将获取到的所有信息加入到列表中
    else:
        print('Error!Can not get AvePowCsum,TestNumber is',testNumber,'in',StartTime,'~',StopTime) #没有计算出平均功耗为异常状态，打印出异常的实验编号和时间段
data=sorted(data,key=lambda x:(x[0],x[1],x[2])) #按照实验编号，日期，时间的顺序进行排序
print('Test\tDate\t\tTime\t\tratio\tavgPow')
for row in data:
    for item in row:
        print(item,end='\t')
    print()